/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package ru.bfpro.cftsourceadmin;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.plaf.metal.MetalIconFactory;
import org.tmatesoft.svn.core.SVNCommitInfo;
import org.tmatesoft.svn.core.SVNDepth;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.io.SVNRepository;
import org.tmatesoft.svn.core.wc.SVNChangelistClient;
import org.tmatesoft.svn.core.wc.SVNClientManager;
import org.tmatesoft.svn.core.wc.SVNCommitClient;
import org.tmatesoft.svn.core.wc.SVNInfo;
import org.tmatesoft.svn.core.wc.SVNLogClient;
import org.tmatesoft.svn.core.wc.SVNRevision;
import org.tmatesoft.svn.core.wc.SVNUpdateClient;
import org.tmatesoft.svn.core.wc.SVNWCClient;

/**
 *
 * @author fbn
 */
public class CFTRepository {
    static String Path;
    static String User;
    static String Password;
    static SVNRepository repo;
    static SVNClientManager svnClientManager;

    static String wcPath;
            
    public static void deleteDirectory(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i=0; i<children.length; i++) {
                File f = new File(dir, children[i]);
                deleteDirectory(f);
            }
            dir.delete();
        } else dir.delete();        
    }
    
    /**
     * Инициализация функционала для работы с репозиторием
     */
    public static void doInit()
    {
        svnClientManager = SVNClientManager.newInstance();
        try {
            // Создаем временный каталог для размещения рабочей копии
            File wcDummyFile = File.createTempFile("wc_dummy","");
            wcPath = wcDummyFile.getParent() + "\\_CftSource_wc.tmp";
        } catch (IOException ex) {
            Logger.getLogger(CFTRepository.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Добавление файла в репозиторий
     * @param path
     * @throws SVNException 
     */
    public static void doAdd(File path) throws SVNException {
        SVNWCClient wcClient = svnClientManager.getWCClient();
        SVNInfo info;
        try {
            info = wcClient.doInfo(path,SVNRevision.UNDEFINED);
        } catch (SVNException e) {
            wcClient.doAdd(path,
                            true,
                            false,
                            true,
                            SVNDepth.INFINITY,
                            false,
                            true);
        }
    }
    
    /**
     * 
     * @param dstUrl - Каталог в репозитории
     * @param logMessage - Сообщение в лог 
     * @throws IOException 
     */
    public static void doCommit(String repPath, String logMessage) throws IOException, SVNException
    {
        SVNCommitClient commitClient = svnClientManager.getCommitClient();
        SVNCommitInfo info;
        
        // Сохраняем файл с содержимым блока
        BufferedWriter outWriter;
        // EXECUTE
        outWriter = new BufferedWriter(new FileWriter(wcPath+"\\EXECUTE.TXT"));
        outWriter.write(CFTMethod.SourceExecute);
        outWriter.close();
        doAdd(new File(wcPath + "\\EXECUTE.TXT"));
        // VALIDATE
        outWriter = new BufferedWriter(new FileWriter(wcPath+"\\VALIDATE.TXT"));
        outWriter.write(CFTMethod.SourceValidate);
        outWriter.close();
        doAdd(new File(wcPath + "\\VALIDATE.TXT"));
        // PUBLIC
        outWriter = new BufferedWriter(new FileWriter(wcPath+"\\PUBLIC.TXT"));
        outWriter.write(CFTMethod.SourcePublic);
        outWriter.close();
        doAdd(new File(wcPath + "\\PUBLIC.TXT"));
        // PRIVATE
        outWriter = new BufferedWriter(new FileWriter(wcPath+"\\PRIVATE.TXT"));
        outWriter.write(CFTMethod.SourcePrivate);
        outWriter.close();
        doAdd(new File(wcPath + "\\PRIVATE.TXT"));
        // VBSCRIPT
        outWriter = new BufferedWriter(new FileWriter(wcPath+"\\VBSCRIPT.TXT"));
        outWriter.write(CFTMethod.SourceVBScript);
        outWriter.close();
        doAdd(new File(wcPath + "\\VBSCRIPT.TXT"));

        try {
            info = commitClient.doCommit(new File[]{new File(wcPath)}, 
                                false, 
                                logMessage, 
                                null, 
                                null,
                                false,
                                true, 
                                SVNDepth.INFINITY);
        } catch (SVNException e) {
            Logger.getLogger(frmModel.class.getName()).log(Level.SEVERE, null, e);
        }
    }

    static void doCheckout(String repPath, String logMessage) {
        File td = new File(wcPath);
        // Проверить что каталог на диске уже существует
        if (td.exists()==true) {
            deleteDirectory(td);
        }
        td.mkdir();
        
        try {
            SVNLogClient logClient = svnClientManager.getLogClient();
            SVNUpdateClient updateClient = svnClientManager.getUpdateClient();
            SVNURL dstUrl = SVNURL.parseURIEncoded(repo.getLocation() + "/" + repPath);
            try {
                    // Пробуем получить каталог в репозитории
                    logClient.doList(dstUrl, SVNRevision.HEAD, SVNRevision.HEAD, true, true, null);
                } catch (SVNException e) {
                    // Значит его нет - создаем
                    SVNCommitClient commitClient = svnClientManager.getCommitClient();
                    SVNCommitInfo info;
                    info = commitClient.doMkDir(new SVNURL[]{dstUrl}, logMessage, null, true);
                }
                // Делаем чекаут в созданную временную рабочую копию
                updateClient.doCheckout(dstUrl,
                        new File(wcPath),
                        SVNRevision.HEAD,
                        SVNRevision.HEAD,
                        SVNDepth.INFINITY,
                        true);
        } catch (SVNException ex) {
            Logger.getLogger(CFTRepository.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }
}
